#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : function.py
# @Author: shadow
# @Date  : 2020/2/4
# @Desc  :

# 简单实现函数map， reduce， filter

from collections.abc import Iterable,Iterator
from functools import reduce

list_str = [0,1,2,3,4,5]


# map
def fn_map(fn, data):
    if isinstance(data, Iterable):
        yield from (fn(i) for i in data)
    else:
        print("err data")


def fn_reduce(fn, data):
    if isinstance(data, Iterable):
        value = data[0]
        for i in data[1:]:
            value = fn(value, i)
        return value
    else:
        print("err data")


def fn_filter(fn, data):
    if isinstance(data, Iterable):
        list_filter = []
        for i in data:
            if fn == None:
                """
                这里用if fn 试试可以不？
                """
                if i:
                    list_filter.append(i)
            else:
                if fn(i):
                    list_filter.append(i)
        yield from list_filter
    else:
        print("err data")


m1 = map(lambda x: x*2, list_str)
m2 = fn_map(lambda x: x*2, list_str)

r1 = reduce(lambda x,y: x*y, list_str)
r2 = fn_reduce(lambda x,y: x*y, list_str)

f1 = filter(lambda x: x%2, list_str)
f2 = fn_filter(lambda x: x%2, list_str)
print(list(m1), list(m2), r1, r2, list(f1), list(f2))

